<template>
  <div>
    <el-upload
      :class="{ hide: fileList.length >= limit }"
      ref="imageUploadRef"
      multiple
      :file-list="fileList"
      :action="uploadImgUrl"
      :headers="headers"
      :limit="limit"
      accept="image/*"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :before-upload="handleBeforeUpload"
      :before-remove="handleDelete"
      :on-preview="handlePictureCardPreview"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="maxSize">
        大小不超过 <b style="color: #f56c6c">{{ maxSize }}MB</b>
      </template>
      <template v-if="fileType">
        ，格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      <template v-if="aspectRatio">
        ，宽高比 <b style="color: #f56c6c">{{ aspectRatioStr }}</b>
      </template>
      的图片
    </div>
  </div>
  <el-dialog v-model="dialogVisible" :show-close="false">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ComponentInternalInstance, computed, getCurrentInstance, ref, watch } from 'vue'
import { UploadFile, type UploadProps } from 'element-plus'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imageUploadRef = ref<ElUploadInstance>()
const baseUrl = 'http://10.10.10.3:27080'
const headers = {
  Authorization:
    'Bearer ' +
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJzeXNfdXNlcjoxIiwicm5TdHIiOiJOak1Cc2hicm5yZ3dxVU1saUNHbjg2RzAwWDloTUJsdiIsImNsaWVudGlkIjoiZTVjZDdlNDg5MWJmOTVkMWQxOTIwNmNlMjRhN2IzMmUiLCJ0ZW5hbnRJZCI6IjAwMDAwMCIsInVzZXJJZCI6MSwiZGVwdElkIjoxMDN9.FfT7_3K5i4MnTzbj9hm38aW1LeIA5nYiOxq1eCtVsJ0',
  clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e'
}
const uploadImgUrl = ref(baseUrl + '/resource/oss/upload') // 上传的图片服务器地址
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  fileType: {
    type: Array,
    default: () => ['jpg', 'jpeg', 'png']
  },
  limit: {
    type: Number,
    default: 9
  },
  maxSize: {
    type: Number,
    default: 5
  },
  aspectRatio: {
    // 图片宽高比
    type: Number
  },
  aspectRatioStr: {
    // 图片宽高比
    type: String
  },
  isShowTip: {
    type: Boolean,
    default: true
  }
})
const number = ref(0)
const uploadList = ref<any[]>([]) // 上传图片列表
const fileList = ref<any[]>(props.modelValue)
const showTip = computed(() => props.isShowTip && (props.fileType || props.maxSize || props.aspectRatio))
//监听父组件的值
watch(
  () => props.modelValue,
  () => {
    fileList.value = props.modelValue
  }
)

// 通过emit将值传递给父组件
emit('update:modelValue', fileList)

const handleBeforeUpload = async (file: any) => {
  const { type, size } = file
  const { fileType, maxSize } = props
  if (!fileType.includes(type.split('/')[1].toLowerCase())) {
    proxy?.$modal.msgError(`图片格式不正确, 请上传${fileType.join('/')}图片格式!`)
    return false
  }
  if (size / 1024 / 1024 > maxSize) {
    proxy?.$modal.msgError(`图片大小不能超过${maxSize}MB!`)
    return false
  }
  if (props.aspectRatio) {
    await verificationPicPx(file)
  }
  number.value++
}
// 图片比例校验
const verificationPicPx = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target?.result as string
      img.onload = () => {
        const { width, height } = img
        const ratio = width / height
        if (ratio !== props.aspectRatio) {
          proxy?.$modal.msgError(`图片宽高比不符合要求！`)
          reject(false)
        } else {
          resolve(true)
        }
      }
    }
  })
}

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId })
    uploadedSuccessfully()
  } else {
    number.value--
    proxy?.$modal.closeLoading()
    proxy?.$modal.msgError(res.msg)
    imageUploadRef.value?.handleRemove(file)
    uploadedSuccessfully()
  }
}
// 上传结束处理
const uploadedSuccessfully = () => {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value)
    uploadList.value = []
    number.value = 0
    emit('update:modelValue', fileList)
  }
}

// 文件个数超出
const handleExceed = () => {
  proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传图片失败')
}

// 删除图片
const handleDelete = (file: UploadFile): boolean => {
  const findex = fileList.value.map((f) => f.name).indexOf(file.name)
  console.log(findex)
  if (findex > -1 && uploadList.value.length === number.value) {
    // const ossId = fileList.value[findex].ossId
    // delOss(ossId)
    fileList.value.splice(findex, 1)
    emit('update:modelValue', fileList)
    return false
  }
  return true
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>

<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}
</style>
